package com.example.demo.web;



import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.domain.Course;
import com.example.demo.domain.Order;
import com.example.demo.domain.Person;

import lombok.extern.slf4j.Slf4j;

import com.example.demo.domain.Course.Type;


@Slf4j
@Controller
@RequestMapping("/select")
public class OrderController {
	@ModelAttribute
	public void addIngredientsToModel(Model model) {
		List<Course> ingredients = Arrays.asList(
				  new Course("java web", Type.CLASS),
				  new Course("python", Type.CLASS),
				  new Course("C++", Type.CLASS),
				  new Course("Swift", Type.CLASS),
				  new Course("C#", Type.CLASS),
				  new Course("Machine learning", Type.CLASS),
				  new Course("AI", Type.CLASS),
				  new Course("Java", Type.CLASS),
				  new Course("Matlab", Type.CLASS),
				  new Course("Database", Type.CLASS)
				);
		Type[] types = Course.Type.values();
		for (Type type : types) {
		  model.addAttribute(type.toString().toLowerCase(),
		      filterByType(ingredients, type));
		}
	}
	@GetMapping
	public String orderForm(Model model) {
		model.addAttribute("select",new Order());
		return "Select";
	}
	 @PostMapping
	 public String processDesing(@Valid @ModelAttribute("select") Person select,Errors errors,Model model,
			 HttpServletRequest request,
	            HttpServletResponse response) throws Exception {
		 log.info("Processing select:"+select);
		 formSubmit(request,response);
			return "redirect:/submit";
			
		}
	 private List<Course> filterByType(
		      List<Course> ingredients, Type types) {
		    return ingredients
		              .stream()
		              .filter(x -> x.getType().equals(types))
		              .collect(Collectors.toList());
		  }
	 
	 protected void formSubmit(HttpServletRequest request,
	            HttpServletResponse response)
	            throws Exception {
		 response.setCharacterEncoding("UTF=8");
	        response.setContentType("text/html;charset=UTF-8");
	        //使用request对象的getSession()获取session，如果session不存在则创建一个
	        HttpSession session = request.getSession();
	        String[] values=request.getParameterValues("ingredients");
	        session.setAttribute("data",values);
	    }

}
